// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "CaePipeManager.h"
#include <cstdio>
#include "CaeMsgHead.h"

CaePipeManager::CaePipeManager()
{
    pthread_mutex_init(&m_videoQueueMutex, nullptr);
    pthread_mutex_init(&m_audioQueueMutex, nullptr);
    pthread_mutex_init(&m_cmdQueueMutex, nullptr);
    pthread_mutex_init(&m_channelQueueMutex, nullptr);
    pthread_mutex_init(&m_imeQueueMutex, nullptr);
    pthread_mutex_init(&m_virtualDeviceQueueMutex, nullptr);
};

CaePipeManager &CaePipeManager::GetInstance()
{
    static CaePipeManager instance;
    return instance;
};

void CaePipeManager::WriteFully(uint8_t *buff, uint32_t size, uint8_t type)
{
    auto *tempData = new (std::nothrow) CaePipeData();
    if (tempData == nullptr) {
        LOGE("Failed to write video data to queue, size:%d.", size);
        return;
    }
    bool initState = tempData->Init(buff, size, type);
    if (!initState) {
        delete tempData;
    }
    switch (type) {
        case CAE_MSG_VIDEO: {
            pthread_mutex_lock(&m_videoQueueMutex);
            m_videoQueue.push(tempData);
            pthread_mutex_unlock(&m_videoQueueMutex);
            break;
        }
        case CAE_MSG_AUDIO: {
            pthread_mutex_lock(&m_audioQueueMutex);
            m_audioQueue.push(tempData);
            pthread_mutex_unlock(&m_audioQueueMutex);
            break;
        }
        case CAE_MSG_CONTROL: {
            pthread_mutex_lock(&m_cmdQueueMutex);
            m_cmdQueue.push(tempData);
            pthread_mutex_unlock(&m_cmdQueueMutex);
            break;
        }
        case CAE_MSG_CHANNEL: {
            pthread_mutex_lock(&m_channelQueueMutex);
            m_channelQueue.push(tempData);
            pthread_mutex_unlock(&m_channelQueueMutex);
            break;
        }
        case CAE_MSG_IME: {
            pthread_mutex_lock(&m_imeQueueMutex);
            m_imeQueue.push(tempData);
            pthread_mutex_unlock(&m_imeQueueMutex);
            break;
        }
        case CAE_MSG_VIRTUAL_CAMERA:
        case CAE_MSG_VIRTUAL_MICROPHONE:
        case CAE_MSG_VIRTUAL_SENSOR:
            pthread_mutex_lock(&m_virtualDeviceQueueMutex);
            m_virtualDeviceQueue.push(tempData);
            pthread_mutex_unlock(&m_virtualDeviceQueueMutex);
            break;
        default: {
            LOGD("No type matched, type is %d", type);
            break;
        }
    }
};

CaePipeManager::~CaePipeManager()
{
    CaePipeData *tempData = nullptr;

    while (!m_videoQueue.empty()) {
        tempData = m_videoQueue.front();
        if (nullptr != tempData) {
            free((void *) tempData->GetBuffer());
            m_videoQueue.pop();
            delete tempData;
        }
    }
    while (!m_audioQueue.empty()) {
        tempData = m_audioQueue.front();
        if (nullptr != tempData) {
            free((void *) tempData->GetBuffer());
            m_audioQueue.pop();
            delete tempData;
        }
    }

    while (!m_cmdQueue.empty()) {
        tempData = m_cmdQueue.front();
        if (nullptr != tempData) {
            free((void *) tempData->GetBuffer());
            m_cmdQueue.pop();
            delete tempData;
        }
    }

    while (!m_channelQueue.empty()) {
        tempData = m_channelQueue.front();
        if (nullptr != tempData) {
            free((void *) tempData->GetBuffer());
            m_channelQueue.pop();
            delete tempData;
        }
    }

    while (!m_imeQueue.empty()) {
        tempData = m_imeQueue.front();
        if (nullptr != tempData) {
            free((void *) tempData->GetBuffer());
            m_imeQueue.pop();
            delete tempData;
        }
    }

    while (!m_virtualDeviceQueue.empty()) {
        tempData = m_virtualDeviceQueue.front();
        if (nullptr != tempData) {
            free((void *) tempData->GetBuffer());
            m_virtualDeviceQueue.pop();
            delete tempData;
        }
    }

    pthread_mutex_destroy(&m_videoQueueMutex);
    pthread_mutex_destroy(&m_audioQueueMutex);
    pthread_mutex_destroy(&m_cmdQueueMutex);
    pthread_mutex_destroy(&m_channelQueueMutex);
    pthread_mutex_destroy(&m_imeQueueMutex);
    pthread_mutex_destroy(&m_virtualDeviceQueueMutex);
}

int CaePipeManager::ReadSize(uint8_t type) const
{
    switch (type) {
        case CAE_MSG_AUDIO:
            return (int)m_audioQueue.size();
        case CAE_MSG_VIDEO:
            return (int)m_videoQueue.size();
        case CAE_MSG_CONTROL:
            return (int)m_cmdQueue.size();
        case CAE_MSG_CHANNEL:
            return (int)m_channelQueue.size();
        case CAE_MSG_IME:
            return (int)m_imeQueue.size();
        case CAE_MSG_VIRTUAL_DEVICE:
            return (int)m_virtualDeviceQueue.size();
        default:
            return 0;
    }
};

CaePipeData *CaePipeManager::ReadOnePkt(uint8_t type)
{
    CaePipeData *pipeData;
    pipeData = nullptr;

    switch (type) {
        case CAE_MSG_AUDIO: {
            pthread_mutex_lock(&m_audioQueueMutex);
            if (!m_audioQueue.empty()) {
                pipeData = m_audioQueue.front();
                m_audioQueue.pop();
                pthread_mutex_unlock(&m_audioQueueMutex);
                break;
            } else {
                pthread_mutex_unlock(&m_audioQueueMutex);
                return pipeData;
            }
        }
        case CAE_MSG_VIDEO: {
            pthread_mutex_lock(&m_videoQueueMutex);
            if (!m_videoQueue.empty()) {
                pipeData = m_videoQueue.front();
                m_videoQueue.pop();
                pthread_mutex_unlock(&m_videoQueueMutex);
                break;
            } else {
                pthread_mutex_unlock(&m_videoQueueMutex);
                return pipeData;
            }
        }
        case CAE_MSG_CONTROL: {
            pthread_mutex_lock(&m_cmdQueueMutex);
            if (!m_cmdQueue.empty()) {
                pipeData = m_cmdQueue.front();
                m_cmdQueue.pop();
                pthread_mutex_unlock(&m_cmdQueueMutex);
                break;
            } else {
                pthread_mutex_unlock(&m_cmdQueueMutex);
                return pipeData;
            }
        }
        case CAE_MSG_CHANNEL: {
            pthread_mutex_lock(&m_channelQueueMutex);
            if (!m_channelQueue.empty()) {
                pipeData = m_channelQueue.front();
                m_channelQueue.pop();
                pthread_mutex_unlock(&m_channelQueueMutex);
                break;
            } else {
                pthread_mutex_unlock(&m_channelQueueMutex);
                return pipeData;
            }
        }
        case CAE_MSG_IME: {
            pthread_mutex_lock(&m_imeQueueMutex);
            if (!m_imeQueue.empty()) {
                pipeData = m_imeQueue.front();
                m_imeQueue.pop();
                pthread_mutex_unlock(&m_imeQueueMutex);
                break;
            } else {
                pthread_mutex_unlock(&m_imeQueueMutex);
                return pipeData;
            }
        }
        case CAE_MSG_VIRTUAL_DEVICE: {
            pthread_mutex_lock(&m_virtualDeviceQueueMutex);
            if (!m_virtualDeviceQueue.empty()) {
                pipeData = m_virtualDeviceQueue.front();
                m_virtualDeviceQueue.pop();
                pthread_mutex_unlock(&m_virtualDeviceQueueMutex);
                break;
            } else {
                pthread_mutex_unlock(&m_virtualDeviceQueueMutex);
                return pipeData;
            }
        }
        default: {
            LOGD("no type matched, type is %d", type);
            break;
        }
    }

    return pipeData;
}

void CaePipeManager::AppendData(uint8_t *data, size_t size, bool addMsgHeader, uint8_t type)
{
    uint8_t *toAppendData = nullptr;
    size_t toAppendDataSize = size;
    StreamMsgHead msghead {};
    if (addMsgHeader) {
        msghead.checksum = (uint8_t)GET_CAE_CHECKSUM(type);
        msghead.magicWord = htons(CAE_STREAM_DELIMITER_MAGICWORD);
        msghead.size = htonl(size);
        msghead.type = type;
        toAppendDataSize = toAppendDataSize + sizeof(STREAM_MSG_HEAD);
    }
    toAppendData = static_cast<uint8_t *>(malloc(toAppendDataSize));
    if (toAppendData == nullptr) {
        LOGE("Failed to create toAppendData, type:%d.", type);
        return;
    }
    if (memset_s(toAppendData, toAppendDataSize, '\0', toAppendDataSize) != EOK) {
        LOGE("Failed to memset toAppendData, type: %d.", type);
        free(toAppendData);
        toAppendData = nullptr;
        return;
    }

    if (addMsgHeader) {
        size_t msgHeaderSize = sizeof(STREAM_MSG_HEAD);
        if (memcpy_s(toAppendData, msgHeaderSize, &msghead, msgHeaderSize) != EOK) {
            LOGE("Failed to memcpy msgHead, type: %d.", type);
            free(toAppendData);
            toAppendData = nullptr;
            return;
        }
        if (memcpy_s(toAppendData + msgHeaderSize, size, data, size) != EOK) {
            LOGE("Failed to memcpy data, type: %d.", type);
            free(toAppendData);
            toAppendData = nullptr;
            return;
        }
    } else {
        if (memcpy_s(toAppendData, toAppendDataSize, data, toAppendDataSize) != EOK) {
            LOGE("Failed to memcpy data, type: %d.", type);
            free(toAppendData);
            toAppendData = nullptr;
            return;
        }
    }
    CaePipeManager::GetInstance().WriteFully(toAppendData, toAppendDataSize, type);
}
